/*
 * @Date: 2022-03-02 10:32:10
 * @LastEditors: 春贰
 * @gitee: https://gitee.com/chun22222222
 * @github: https://github.com/chun222
 * @Desc:markdown
 * @LastEditTime: 2022-12-12 14:03:39
 * @FilePath: \zebra_webapi\system\service\printService\printService.go
 */

package printService

import (
	// "fmt"

	"fmt"
	"net"
	"strings"
	"time"
	"zebra_webapi/system/common/template"
	"zebra_webapi/system/core/config"

	"golang.org/x/text/encoding/simplifiedchinese"
	// "github.com/gin-gonic/gin"
	//"zebra_webapi/system/model/RequestModel"
	//"sort"
)

type PrintService struct {
}

func (_this *PrintService) Print(tplname string, printMap map[string]interface{}) error {

	var err error
	var printstr string

	for k, v := range printMap {
		//替换所有\r\n
		printMap[k] = strings.ReplaceAll(fmt.Sprintf("%v", v), "\r\n", "")
	}

	conn, err := net.Dial("tcp", config.Instance().Config.App.PrinerIpPort)
	if err != nil {
		fmt.Println("err :", err)
		return err
	}

	//固定字段
	//datetime ,time ,
	datetime := time.Now().Format("2006-01-02 15:04:05")
	date := time.Now().Format("2006-01-02")
	time := time.Now().Format("15:04:05")
	if printMap == nil {
		printMap = make(map[string]interface{})
	}

	printMap["datetime"] = datetime
	printMap["time"] = time
	printMap["date"] = date
	err, printstr = template.PrintTemlate(tplname, printMap)
	if err != nil {
		fmt.Println("tempaltefile failed, err:", err)
		return err
	}

	h, err := simplifiedchinese.GBK.NewEncoder().Bytes([]byte(printstr))
	if err != nil {
		return fmt.Errorf("转码失败" + err.Error())
	}
	_, err = conn.Write(h) //发送打印zpl文本

	if err != nil {
		fmt.Println("recv failed, err:", err)
		return err
	}
	defer conn.Close() // 关闭连接
	return nil

}
